/**
 * 购物车
 * @author Qasim <15750783791@163.com>
 * @version 2016/11/18 1.0
 */
document.addEventListener('plusready' , ready , false );

var self = memberInfo = payment = '';

var totalmoney = 0;

function ready(){
	self = plus.webview.currentWebview();
	userInfo();
	goodscartInfo();
	
	//删除处理
	$('#promptBtn').on('click' , function(){
		plus.nativeUI.confirm('温馨提示:确定要将选中的商品移除购物车吗？' , function(e){
			if(e.index == 0){
				deleteGoodscart();
			}
		} , '电子阅读' , ['确定' , '取消']);
	})	
	
	//结算
	$('.mui-btn').on('click' , function(){ 
		var balance = memberInfo.money;
		$('.total_price').text(totalmoney + ' 元');
		if(parseInt(balance) > parseInt(totalmoney)){
			$('.account_price').text(balance + ' 元');
			$('.pay_type').text('余额支付');
			$(".alert.buy").slideToggle()
			$(".alert-back").toggle();
			payment = 2;
		}else{
			payment = 5;
			$('.account_price').html(balance + ' 元 &nbsp;&nbsp;<span style="color:black">余额不足 请使用短信支付<span>' );
			$('.pay_type').text('短信支付');
		}
	})
	
	/**
	 * 支付
	 */
	$('.balance_pay').on('click' , function(){
		plus.nativeUI.confirm('温馨提示:确定要购买这些商品吗？' , function(e){
			if(e.index == 0){
				var ids = '';
				var checkbox_length = $('input[name=checkbox]:checked').length;
				$('input[name=checkbox]:checked').each(function(){ 
					var __this = $(this).parent().parent().parent().find('.text');
					console.log(__this.html()) 
					if(ids == ''){
						ids = ',' + __this.attr('data-id') + ',';
					}else{
						ids +=  __this.attr('data-id') +',';
					}
				})
				$.ajax({  
					type:"post",
					url:apiRoot + "/Home/Order/addOrder/",
					data:{
						ids : ids ,
						uid : memberInfo.aid,
						payment : payment,
						buy_type : 'goodscart'
					},
					beforeSend:function(){
						plus.nativeUI.showWaiting('结算中...');
					},
					complete:function(){
						plus.nativeUI.closeWaiting();
					},
					success :function(data){
						if(data > 0){ 
							toast('购买成功');
							$(".alert.buy").slideUp()
							$(".alert-back").toggle();
							deleteGoodscart(parseInt($('.total_price').text()));
						}
					},
					error:function(e){
						errorPrompt(e);
					}
				});
			}
		} , '电子阅读' , ['确定' , '取消']);
	})
	
}	

/**
 * 用户信息
 */
function userInfo(){
	memberInfo = plus.storage.getItem('memberInfo');
	memberInfo = $.parseJSON(memberInfo);  
}

function deleteGoodscart(price){
	if(!price)price = 0;
	var ids = '';
	var checkbox_length = $('input[name=checkbox]:checked').length;
	$('input[name=checkbox]:checked').each(function(){ 
		var __this = $(this);
		if(ids == ''){
			ids = ',' + __this.attr('value') + ',';
		}else{
			ids +=  __this.attr('value') +',';
		}
	})
	$.ajax({  
		type:"post",
		url:apiRoot + "/Home/Goodscart/deleteGoodscart/",
		data:{
			ids : ids ,
			uid:memberInfo.aid,
			price : price
		},
		beforeSend:function(){
			plus.nativeUI.showWaiting('删除中...');
		},
		complete:function(){
			plus.nativeUI.closeWaiting();
		},
		success :function(data){
			var res = eval('('+data+')');
			if(res){ 
				toast('操作成功');
				$('input[name=checkbox]:checked').each(function(){ 
					$(this).parent().parent().parent().parent().parent().remove();
					document.getElementById('allBox').checked = false;
					totalmoney = 0;
					$('.totalmoney').text('￥' + totalmoney);
				})
				if(self.page){
					mui.fire(plus.webview.getWebviewById(self.page) , 'update_goodscart' , {
						num : checkbox_length
					})
				}
				plus.storage.setItem('memberInfo' , data+'');
				userInfo();
			}
		},
		error:function(e){
			errorPrompt(e);
		}
	});
}


/**
 * 购物车
 */
function goodscartInfo(){ 
	$.ajax({
		type:"post",  
		url:apiRoot + "/Home/Goodscart/myGoodscart/", 
		data:{
			uid :  memberInfo.aid 
		}, 
		beforeSend:function(){
			plus.nativeUI.showWaiting('加载中...');
		}, 
		complete:function(){
			plus.nativeUI.closeWaiting();
		},
		dataType:'json',
   		success : function(data){   
   			if(data){
   				var money = 0;
				$.each(data, function(k , v) {
					var html = '<div class="list-p"><ul class="mui-table-view"><li class="mui-table-view-cell mui-media" >';
						html += '<div class="mui-pull-left wid1"><div class="mui-checkbox mui-left">';	
						html += '<input name="checkbox" type="checkbox" checked="checked" value="'+v.id+'" id="box'+v.id+'"></div></div>';
						html += '<div class="mui-pull-left wid2 text" data-id="'+v.aid+'" data-price="'+v.attribute[0].price+'"><img class="mui-media-object mui-pull-left" src="'+v.attribute[0].litpic+'">';
						html += '<div class="mui-media-body"><span>'+v.attribute[0].name+'</span><p class="mui-ellipsis" style="padding: 5px 0 7px; font-size: 13px;">';
						html += '<span>'+v.attribute[0].author+'</span></p><p>';
					   	if(parseInt(v.attribute[0].price) > 0 && parseInt(v.attribute[0].discount_price) == 0){
					   		totalmoney += parseFloat(v.attribute[0].price);
						   	html += '<span class="mui-red">'+v.attribute[0].price+' 元</span>';
					   	}else{
					   		totalmoney += parseFloat(v.attribute[0].discount_price);
							html += '<span class="mui-red">'+v.attribute[0].discount_price+'</span><span style="text-decoration:line-through;margin: 0 5px;">'+v.attribute[0].price+'</span> 元 </span>';
					   	}
					   	money = totalmoney;
					   	html += '</p></div></div></li></ul></div>';
					$('.lists').append(html);
				});
				 
				$('.totalmoney').text('￥' + totalmoney);
				var checked_length = $('input[name=checkbox]:checked').length;
   				if(checked_length > 0) $('#allBox').attr('checked' , true);
				//前往书籍详情
				$('.text').unbind();
				$('.text').on('click'  , function(){
					bookDetails($(this).attr('data-id') ,$(this).attr('data-price') )
				})
				
				//单选  逻辑处理
				var checkbox_len = $('input[name=checkbox]').length;
				$('input[name=checkbox]').unbind();
				$('input[name=checkbox]').on('click' , function(){
					showWaiting('' , 100);
					var boxid =  $(this).attr('id'); 
					if(document.getElementById(boxid).checked){
						var checked_length = $('input[name=checkbox]:checked').length;
						if(checkbox_len === checked_length){ 
							document.getElementById('allBox').checked = true;
						}
						totalmoney += parseInt(parseInt($(this).parent().parent().parent().find('.mui-red').text()));
						$('.totalmoney').text('￥' + totalmoney);
					}else{
						document.getElementById('allBox').checked = false;
						totalmoney -= parseInt(parseInt($(this).parent().parent().parent().find('.mui-red').text()));
						$('.totalmoney').text('￥' + totalmoney);
					}
				});
				
				//全选 反选  逻辑处理
				$(".all-chose>input[type='checkbox']").on("click",function(){
					if($(this).is(":checked")){ 
						totalmoney = money;
						$("input[name='checkbox']").each(function(){
							$(this).prop('checked',true);
						});
						$('.totalmoney').text('￥ ' + totalmoney)
					}else{
						$("input[name='checkbox']").each(function(){
							$(this).prop('checked',false)
						});
						totalmoney = 0;
						$('.totalmoney').text('￥  ' + totalmoney);
					}
				})
	   		}
    	},
   		error :function(e){
   			errorPrompt(e);	
   		}
   	})	
}
